package com.aponisipsis.gl3d.geometry;

import static org.lwjgl.opengl.GL11.*;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Quaternion;
import org.lwjgl.util.vector.Vector3f;
import org.newdawn.slick.opengl.Texture;

import com.aponisipsis.gl3d.data.ResourceManager;

/**
 * 
 * @author Amnimhops Only 1 texture Texture is per-mesh, not per-face
 * 
 */
public class Mesh2D extends Object3D {
	String name;
	int layer;
	Transform transform;
	String textureId;
	
	Vertex[] vertices;
	Face[] faces;
	float[][][] uv;
	
	public Mesh2D(Vertex[] vertices, Face[] faces, float[][][] uv) {
		this.vertices = vertices;
		this.faces = faces;
		this.uv = uv;
		transform = new Transform();
		this.layer = 0;
	}

	public int getLayer() {
		return layer;
	}
	
	public Face[] getFaces(){
		return faces;
	}
	
	public Vertex[] getVertices(){
		return vertices;
	}

	public void setLayer(int layer) {
		this.layer = layer;
	}

	// public void setAmature(Armature armature){
	// this.armature=armature;
	// }
	public void setTextureId(String textureId){
		this.textureId = textureId;
	}
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	/*
	 * 
	 * 
	 */
	public void render() {
		int mode = 0;
		
		FloatBuffer fb = transform.getStoredMatrix();
		
		// Set texture
		
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		
		ResourceManager.getTexture(textureId).bind();
//		
//		GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
//		GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
//		GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
//		
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glLoadMatrix(fb);
		
		
		int fid = 0;
		for (Face face : faces){
			if (face.vtx.length == 3) {
				mode = GL_TRIANGLES;
			} else if (face.vtx.length == 4) {
				mode = GL_QUADS;
			} else {
				mode = GL_POLYGON;
			}

			glBegin(mode);
			int vid = 0;
			for(Vertex v:face.vtx){
				//System.out.println(String.format("Mesh %s Vertex %d (%.3f,%.3f,%.3f)\n",name,vid,v.position[0],v.position[1],v.position[2]));
				glColor3f(1,1,1);
				glNormal3f(0,0,1);
				glTexCoord2f(uv[fid][vid][0],uv[fid][vid][1]);
				glVertex3f(v.position[0],v.position[1],-layer/20);
				vid++;
			}
			glEnd();
			fid++;
		}			
	}

	public Transform getTransform() {
		return transform;
	}
}
